﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Logging;

namespace JX.Infrastructure.Framework.Filter
{
    /// <summary>
    /// 自定义异常处理过滤器。在Startup.cs文件的ConfigureServices方法中，添加services.AddControllersWithViews(options =>{options.Filters.Add《CustomExceptionFilterAttribute》();})
    /// </summary>
    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        private readonly ILogger<CustomExceptionFilterAttribute> _logger;
        private readonly IModelMetadataProvider _modelMetadataProvider;
        /// <summary>
        /// 构造器注入
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="modelMetadataProvider"></param>
        public CustomExceptionFilterAttribute(ILogger<CustomExceptionFilterAttribute> logger, IModelMetadataProvider modelMetadataProvider)
        {
            _logger = logger;
            _modelMetadataProvider = modelMetadataProvider;
        }
        /// <summary>
        /// 发生异常时 进入
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            _logger.LogError($"在响应 {context.HttpContext.Request.Path} 时出现异常，信息：{context.Exception.ToString()}");

            if (!context.ExceptionHandled)        //异常未被处理
            {
                if (Utility.IsAjaxRequest(context.HttpContext.Request))//ajax请求
                {
                    context.Result = new JsonResult(new
                    {
                        Result = false,
                        Msg = $"发生错误，异常信息：{context.Exception.Message}"
                    });//中断式---请求到这里结束了，不再继续Action
                }
                else
                {
                    var result = new ViewResult { ViewName = "~/Views/Shared/Error.cshtml" };
                    result.ViewData = new ViewDataDictionary(_modelMetadataProvider,context.ModelState);
                    result.ViewData.Add("Exception", context.Exception.Message);
                    context.Result = result;
                }
                context.ExceptionHandled = true;//异常已被处理
            }
        }
    }
}
